<script setup lang="ts">
import {onMounted, ref} from "vue";
import {NAMESPACE_USER} from "../../interface/user.ts";
import {delUser, queryUser, queryUserGroup, userAddToGroup} from "../../api/user.ts";
import UserUpdate from "./UserUpdate.vue";
import UserAdd from "./UserAdd.vue";
import DelDialog from "../DelDialog.vue";
import {ElTable} from "element-plus";
import {messageTip, MessageTipType} from "../../util/common.ts";
import {CommonModel} from "../../interface/commonModel.ts";


const userList = ref<Array<NAMESPACE_USER.UserItem>>([])
const pageInfo = ref<CommonModel.PageInfo>({
  pageSize:10,
  pageNo:1,
  total:0,
})

const currentUser = ref<NAMESPACE_USER.UserItem>({})
const dialogUpdateFormVisible = ref<boolean>(false)
const dialogAddFormVisible = ref<boolean>(false)
const dialogDelFormVisible = ref<boolean>(false)
const selectedIds = ref<Array<string>>([])

const queryUserList = () => queryUser({
  pageSize: pageInfo.value.pageSize,
  pageNo: pageInfo.value.pageNo
})

onMounted(() => {
  queryUserList().then(data => {
    userList.value = data.data
    pageInfo.value.total = data.pageInfo.total
  })
})

const handleEditClick = (user: NAMESPACE_USER.UserItem) => {
  currentUser.value = user;
  dialogUpdateFormVisible.value = true
}

const handleAddClick = () => {
  console.log("handleAddClick")
  dialogAddFormVisible.value = true
}

const multipleTableRef = ref<InstanceType<typeof ElTable>>()

const handleDelClick=(uid?:string)=>{
  selectedIds.value=[]
  if (typeof(uid) == "string"){
    selectedIds.value.push(uid)
  }
  for (let i = 0; i < multipleTableRef.value.getSelectionRows().length; i++) {
    selectedIds.value.push(multipleTableRef.value.getSelectionRows()[i].uid)
  }
  if (selectedIds.value.length === 0){
    messageTip("至少选择一条删除",MessageTipType.ERROR)
  }
  dialogDelFormVisible.value =true
}


const handleSelectionChange =()=>{
  selectedIds.value=[]
  for (let i = 0; i < multipleTableRef.value.getSelectionRows().length; i++) {
    selectedIds.value.push(multipleTableRef.value.getSelectionRows()[i].uid)
  }
}

const closeDialog = (success:boolean)=>{
  currentUser.value = {};
  dialogUpdateFormVisible.value = false
  dialogAddFormVisible.value = false
  dialogDelFormVisible.value = false
  selectedIds.value=[]
  if (success){
    queryUserList().then(data => {
      userList.value = data.data
      pageInfo.value.total = data.pageInfo.total
    })
  }
}

const stateFormat = (row: NAMESPACE_USER.UserItem) => {
  if (row.state === -1) {
    return '锁定状态'
  } else if (row.state === 0) {
    return '初始状态'
  } else if (row.state === 1 || row.state === 2) {
    return '正常状态'
  } else {
    return '异常状态'
  }
}

const handlePageChange = (currentPage:number)=>{
  pageInfo.value.pageNo = currentPage
  queryUserList().then(data => {
    userList.value = data.data
    pageInfo.value.total = data.pageInfo.total
  })
}

const handleSizeChange = (currentPageSize:number)=>{
  pageInfo.value.pageSize = currentPageSize
  queryUserList().then(data => {
    userList.value = data.data
    pageInfo.value.total = data.pageInfo.total
  })
}

const dialogUserGroupVisible = ref(false)
const userGroupList = ref<Array<NAMESPACE_USER.UserGroupItem>>([])
const addUserGroupClick =()=>{
  dialogUserGroupVisible.value = true
  const queryUserGroupList = () => queryUserGroup({
    pageNo:1,
    pageSize:1000
  })
  queryUserGroupList().then(data => {
    userGroupList.value = data.data
    pageInfo.value.total = data.pageInfo.total
  })
}

const saveUserGroup=()=>{
  let userGroupIds = []
  for (let i = 0; i < multipleUserGroupTableRef.value.getSelectionRows().length; i++) {
    userGroupIds.push(multipleUserGroupTableRef.value.getSelectionRows()[i].id)
  }
  if (userGroupIds.length===0){
    messageTip("至少选择一个分组",MessageTipType.WARNING)
    return
  }
  userAddToGroup({
    uids:selectedIds.value,
    userGroupIds:userGroupIds
  }).then(data =>{
    if (data.success){
      messageTip("添加到分组成功",MessageTipType.SUCCESS)
      dialogUserGroupVisible.value = false
    }else {
      messageTip(data.message,MessageTipType.ERROR)
    }
  })
}

const multipleUserGroupTableRef = ref<InstanceType<typeof ElTable>>()

const parentIdFormat = (row: NAMESPACE_USER.UserGroupBase) => {
  if (row.parentId === 0) {
    return '-'
  } else {
    return row.parentId
  }
}
</script>

<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <el-button type="primary" @click="handleAddClick">新增</el-button>
        <el-button type="primary" @click="addUserGroupClick" :disabled="selectedIds.length === 0">加入组</el-button>
        <el-button type="danger" @click="handleDelClick" :disabled="selectedIds.length === 0">删除</el-button>

      </div>
    </template>
    <el-table :data="userList" sele ref="multipleTableRef" @selection-change="handleSelectionChange" style="width: 100%">
      <el-table-column type="selection" width="30" />
      <el-table-column type="index" label="序号"/>
      <el-table-column prop="username" label="用户名"/>
      <el-table-column prop="name" label="姓名"/>
      <el-table-column prop="mobile" label="手机号"/>
      <el-table-column prop="idCard" label="身份证号"/>
      <el-table-column prop="email" label="邮箱"/>
      <el-table-column prop="state" :formatter="stateFormat" label="状态"/>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <div>
            <el-button type="warning" round @click="handleEditClick(scope.row)">编辑</el-button>
            <el-button type="danger" v-if="scope.row.uid != 1" round @click="handleDelClick(scope.row.uid)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <div style="float: right;padding-bottom: inherit">
        <el-pagination
            :current-page="pageInfo.pageNo"
            :page-size="pageInfo.pageSize"
            :page-sizes="[10, 20, 30, 50]"
            :small="false"
            :disabled="false"
            :background="false"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageInfo.total"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
        />
      </div>
    </template>
  </el-card>

  <el-dialog v-model="dialogUserGroupVisible" title="选择用户组">
    <el-table :data="userGroupList" ref="multipleUserGroupTableRef">
      <el-table-column type="selection" width="30" />
      <el-table-column prop="name" label="组名称"/>
      <el-table-column prop="id" label="组id"/>
      <el-table-column prop="parentId" :formatter="parentIdFormat" label="父组id"/>
    </el-table>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogUserGroupVisible = false">取消</el-button>
        <el-button type="primary" @click="saveUserGroup">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>


  <user-add @closeDialog="closeDialog" :dialog-form-visible="dialogAddFormVisible" v-if="dialogAddFormVisible"></user-add>
  <user-update @closeDialog="closeDialog" :current-user="currentUser" :dialog-form-visible="dialogUpdateFormVisible" v-if="dialogUpdateFormVisible"></user-update>
  <del-dialog @closeDialog="closeDialog" :del-func="delUser"  :dialog-visible="dialogDelFormVisible" :ids="selectedIds" message="确定删除用户吗?" tips="删除用户" v-if="dialogDelFormVisible"/>
</template>

<style scoped>

</style>